<template>
    <div class="monitoringrules_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
        <ZwTable
            ref="tableRef"
            class="table_box"
            tab-h="calc(100vh - 344px)"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select="onSelect"
            @selection-change="onSelectionChange"
            @select-all="onSelectAll">
            <template #headerOperate>
                <el-button v-auth="'BATCH_OPEN'" :disabled="ids.length == 0" @click="operate(1)"> 批量开启 </el-button>
                <el-button v-auth="'BATCH_CLOSE'" :disabled="ids.length == 0" @click="operate(2)"> 批量关闭 </el-button>
                <el-button v-auth="'BATCH_DEL'" :disabled="ids.length == 0" @click="operate(3)"> 批量删除 </el-button>
                <el-button v-auth="'NEW_RULE'" type="primary" @click="ruleoperate(1)"> 新建规则 </el-button>
            </template>
        </ZwTable>

        <Dialog :app-dialog="newDialog">
            <div class="content">
                <el-form ref="uploadForm" label-width="90px" class="add-member" :model="formData" :rules="rules">
                    <el-form-item label="规则名称" class="form-item" required>
                        <el-input
                            v-model="formData.name"
                            placeholder="请输入规则名称"
                            class="form-label"
                            show-word-limit
                            maxlength="15"></el-input>
                    </el-form-item>
                    <el-form-item label="有效期" required>
                        <el-radio v-model="formData.validity_period_type" :label="1">永久</el-radio>
                        <el-radio v-model="formData.validity_period_type" :label="2">固定期限</el-radio>
                        <el-date-picker
                            v-if="formData.validity_period_type == 2"
                            v-model="time"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            type="datetimerange"
                            :append-to-body="false"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间" />
                    </el-form-item>
                    <el-form-item label="监控渠道" required>
                        <el-radio v-model="formData.monitoring_channels" :label="1">私聊</el-radio>
                        <el-radio v-model="formData.monitoring_channels" :label="2">群聊</el-radio>
                    </el-form-item>
                    <el-form-item label="监控对象" required class="form-option-item">
                        <el-checkbox-group v-model="formData.monitoring_object">
                            <el-checkbox label="1" name="monitoring_object">员工</el-checkbox>
                            <el-checkbox label="2" name="monitoring_object">客户</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="监控敏感词" prop="departments" class="form-item">
                        <el-select
                            v-model="formInline.tag_ids"
                            clearable
                            popper-class="zw-hide_select_option"
                            multiple
                            collapse-tags
                            collapse-tags-tooltip
                            placeholder="选择敏感词"
                            @click="openBatchLabel"
                            @change="changeWord">
                            <el-option
                                v-for="item in tabsList"
                                :key="item.id"
                                :label="item.words_name"
                                :value="item.id">
                                {{ item.words_name }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="监控类型" class="form-check-item">
                        <el-checkbox-group v-model="formData.monitoring_type">
                            <el-checkbox
                                v-for="(item, index) in monitorList"
                                :key="index"
                                :label="item.value + ''"
                                name="monitoring_type"
                                :indeterminate="isIndeterminate"
                                :value="item.value">
                                {{ item.name }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="提醒设置" class="form-item" required>
                        <el-select
                            v-model="formInline.work_user_list"
                            clearable
                            multiple
                            placeholder="请选择员工"
                            popper-class="zw-hide_select_option"
                            :popper-append-to-body="false"
                            @click="opDepart"
                            @change="changeDepart">
                            <el-option v-for="item in creators" :key="item.id" :label="item.name" :value="item.id">
                                {{ item.name }}
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
        </Dialog>
        <Dialog :app-dialog="appDialog">
            <div class="content">{{ content }}</div>
        </Dialog>
        <!-- 选择敏感词标签 -->
        <Newdialog ref="tagRef" @submit="gettag"></Newdialog>
        <!--员工选择-->
        <ZWDepart ref="DepartRef" :type="1" @submit="getDepart"></ZWDepart>
    </div>
    <!-- 搜索 -->
</template>
<script setup lang="tsx">
import { reactive, toRefs, ref, onBeforeMount, onMounted, watch, computed, nextTick } from 'vue';
import { store } from '@/store';
import { ElMessageBox, ElMessage, ElButton } from 'element-plus';
import { init } from 'echarts';
import ZWDepart from '@/components/ZWDepart.vue';
import BatchLabel from '@/components/BatchLabel.vue';
import Newdialog from './Newdialog.vue';
import Dialog from '@/components/Dialog.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { deepCopy } from '@/utils/helper';
import { getSetionId, tableH, reSize } from '@/utils/utils';
import {
    creatRule,
    editRule,
    ruleList,
    deleteList,
    openList,
    closeList,
    getList
} from '@/api/employe/riskmonitoring/monitoringrules';

const tableData = ref([]);
const ids = ref([]);
const rowid = ref([]);
const emit = defineEmits(['submit', 'cancel']);
const isadd = ref(false);
const content = ref('确定开启所选关键词吗?');
const time = ref(['', '']);
const tagRef = ref(null);
const tabsList = ref([]);
let rowData = reactive({});
const tabH = ref('500px');
// 改造开始
const tableRef = ref<HTMLElement | null>(null);
const defaultParams = {
    keywords: '',
    status: '0'
};
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '名称',
            name: 'keywords',
            value: '',
            type: 'input',
            placeholder: '名称搜索'
        },
        {
            label: '状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { name: '全部', id: 0 },
                            { name: '已开启', id: 1 },
                            { name: '已关闭', id: 2 }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = { ...deepCopy(defaultParams), ...v };
};
const reset = (v: any) => {
    tableRef.value?.clearSelection();
    state.searchParams = { ...deepCopy(defaultParams) };
};

// 表格
const tableOption = [
    {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
    },
    {
        prop: 'name',
        label: '名称',
        minWidth: 130
    },
    {
        prop: 'time',
        label: '有效期',
        width: 200,
        render({ row, column, index }) {
            return (
                <>
                    {row.validity_period_type == 1 ? (
                        '永久有效'
                    ) : (
                        <div>
                            <p>{row.validity_period[0]}</p>
                            <p>至</p>
                            <p>{row.validity_period[1]}</p>
                        </div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'pathandobj',
        label: '监控渠道和对象',
        width: 200,
        render({ row, column, index }) {
            const name = {
                1: '员工',
                2: '客户'
            };
            const namelist = row.monitoring_object.map((item: any) => name[item]);
            return (
                <>
                    {row.monitoring_channels == 1 ? (
                        <div>私聊: {namelist.join('、')} </div>
                    ) : (
                        <div>群聊: {namelist.join('、')}</div>
                    )}
                </>
            );
        }
    },
    {
        prop: 'pathandobj',
        label: '监控规则',
        minWidth: 200,
        render({ row, column, index }) {
            const words: any = [];
            row.words_list.forEach((data: any) => {
                words.push(data.words_name);
            });
            row.words = words.join('、');
            const typelist: any = [];
            row.monitoring_type.forEach((val: any, index: any) => {
                monitorList.value.forEach(vals => {
                    if (val == vals.value) {
                        typelist[index] = vals.name;
                    }
                });
            });
            row.voliateType = typelist.join('、');
            return (
                <>
                    <div v-show={row.words_list.length > 0}>敏感词： {row.words} </div>
                    <div v-show={row.monitoring_type.length > 0}>监控类型： {row.voliateType} </div>
                </>
            );
        }
    },
    {
        prop: 'member',
        label: '提醒员工',
        width: 200,
        render({ row, column, index }) {
            return (
                <>
                    <div> {row.staff_list[0]?.name + '等' + row.staff_list?.length + '个员工'}</div>
                </>
            );
        }
    },
    {
        prop: 'violation',
        label: '违规情况',
        width: 200,
        render({ row, column, index }) {
            return (
                <>
                    <div>违规客户： {row.contact_violation_num} </div>
                    <div>违规员工： {row.staff_violation_num} </div>
                    <div>违规群： {row.group_violation_num} </div>
                </>
            );
        }
    },
    {
        prop: 'status',
        label: '状态',
        width: 150,
        render({ row, column, index }) {
            return (
                <>
                    <div>{row.status == 2 ? '已关闭' : '已开启'} </div>
                </>
            );
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 295,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return onBtn(row);
        }
    }
];

const getRowKey = (row: any) => {
    return row.id;
};

const onBtn = (row: any) => {
    switch (row.status) {
        case 1: // 关闭
            return (
                <>
                    <ElButton
                        size="small"
                        v-auth="OPEN"
                        onClick={() => {
                            closeword(row);
                        }}>
                        关闭
                    </ElButton>

                    <ElButton
                        size="small"
                        v-auth="EDIT"
                        onClick={() => {
                            ruleoperate(2, row);
                        }}>
                        编辑
                    </ElButton>

                    <ElButton
                        size="small"
                        v-auth="DEL"
                        onClick={() => {
                            deleteword(row);
                        }}>
                        删除
                    </ElButton>
                </>
            );
        case 2:
            return (
                <>
                    <ElButton
                        size="small"
                        v-auth="OPEN"
                        onClick={() => {
                            closeword(row);
                        }}>
                        开启
                    </ElButton>
                    <ElButton
                        size="small"
                        v-auth="EDIT"
                        onClick={() => {
                            ruleoperate(2, row);
                        }}>
                        编辑
                    </ElButton>

                    <ElButton
                        size="small"
                        v-auth="DEL"
                        onClick={() => {
                            deleteword(row);
                        }}>
                        删除
                    </ElButton>
                </>
            );
    }
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return ruleList;
};
// 选中表格 checkbox
const onSelect = (selection, row) => {
    if (selection.constructor === Array) ids.value = selection.map(v => v.id);
};
// 选择项变更
const onSelectionChange = selection => {};
// 全选
const onSelectAll = selection => {
    ids.value = selection.map(v => v.id);
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 改造结束

const departTypeObj = {
    departData: [], //选中的数据
    itemData: '' //当前传入的数据
};
const formData = reactive({
    name: '',
    validity_period_type: 1, //有效期类型 1-永久有效 2-固定期限
    validity_period_start: '',
    validity_period_end: '',
    monitoring_channels: 1, //监控渠道：1-私聊 2-群聊
    monitoring_object: [], //监控对象： 1-员工 2-客户
    monitoring_type: [], //监控类型： 2-图片 3-链接 4-小程序 5-名片 6-红包 7-音频 8-视频
    staff_id_arr: [], //提醒员工ID数组
    words_id_arr: [] //监控敏感词ID数组
});
const DepartRef = ref(null);
const creators = ref([]);
const formInline = reactive({
    tag_ids: [],
    keywords: '',
    tag_list: [],
    work_user_list: []
});
const monitorList = ref([]);
const isIndeterminate = ref(false);
// 获取监控类型
const getMontorList = () => {
    getList().then((res: any) => {
        monitorList.value = res;
        monitorList.value.forEach((item: any) => {
            item.checked = true;
        });
    });
};
getMontorList();
// 取消
const cancelHandel = () => {
    emit('cancel');
    appDialog.visible = false;
};
//确定删除
const submitHandel = async () => {
    if (appDialog.title == '批量删除提醒' || appDialog.title == '删除提醒') {
        const param = {
            id_arr: appDialog.title == '批量删除提醒' ? ids.value : rowid.value
        };
        deleteList(param).then((res: any) => {
            ElMessage({ message: '删除成功', type: 'success' });
            tableRef.value?.clearSelection();
            appDialog.visible = false;
            // initpage()
            tableRef.value.reload();
        });
    } else if (appDialog.title == '批量开启提醒' || appDialog.title == '开启提醒') {
        const param = {
            id_arr: appDialog.title == '批量开启提醒' ? ids.value : rowid.value
        };
        openList(param).then((res: any) => {
            ElMessage({ message: '开启成功', type: 'success' });
            tableRef.value?.clearSelection();
            appDialog.visible = false;
            // initpage()
            tableRef.value.reload();
        });
    } else {
        const param = {
            id_arr: appDialog.title == '批量关闭提醒' ? ids.value : rowid.value
        };
        closeList(param).then((res: any) => {
            ElMessage({ message: '关闭成功', type: 'success' });
            tableRef.value?.clearSelection();
            appDialog.visible = false;
            // initpage()
            tableRef.value.reload();
        });
    }
};
const operate = (data: any) => {
    appDialog.visible = true;
    appDialog.title = data == 1 ? '批量开启提醒' : data == 2 ? '批量关闭提醒' : '批量删除提醒';
    content.value = data == 1 ? '确定开启所选规则吗?' : data == 2 ? '确定关闭所选规则吗？' : '确定删除所选内容吗？';
};
const appDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '400px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定'
});
const closeword = (data: any) => {
    rowid.value = [];
    appDialog.visible = true;
    appDialog.title = data.status == 1 ? '关闭提醒' : '开启提醒';
    content.value = data.status == 1 ? `确认要关闭【${data.name}】？` : `确认要开启【${data.name}】？`;
    rowid.value.push(data.id);
};
const SelectionChange = (val: any) => {
    ids.value = [];
    val.forEach((item: any) => {
        ids.value.push(item.id);
    });
};
const deleteword = (val: any) => {
    rowid.value = [];
    appDialog.visible = true;
    appDialog.title = '删除提醒';
    content.value = `确认要删除【${val.name}】？`;
    rowid.value.push(val.id);
};
// 新建/编辑规则
const ruleoperate = (num: any, val?: any) => {
    newDialog.title = num == 1 ? '新建规则' : '编辑规则';
    if (num == 2) {
        rowData = val;
        time.value = val.validity_period;
        formInline.tag_ids = [];
        formData.words_id_arr = [];
        formData.words_id_arr = [];
        val.words_list.forEach((item: any, index: any) => {
            formInline.tag_ids[index] = item.id;
            formData.words_id_arr[index] = item.id;
        });
        formInline.work_user_list = [];
        formData.staff_id_arr = [];
        formData.staff_id_arr = [];
        val.staff_list.forEach((item: any, index: any) => {
            formInline.work_user_list[index] = item.id;
            formData.staff_id_arr[index] = item.id;
        });
        tabsList.value = val.words_list;
        creators.value = val.staff_list;
        formData.name = val.name;
        formData.monitoring_channels = val.monitoring_channels;
        formData.monitoring_object = val.monitoring_object;
        formData.validity_period_type = val.validity_period_type;
        formData.monitoring_type = val.monitoring_type;
    } else {
        time.value = ['', ''];
        tabsList.value = [];
        creators.value = [];
        formInline.work_user_list = [];
        formInline.tag_ids = [];
        for (const key in formData) {
            if (key == 'name' || key == 'validity_period_start') {
                formData[key] = '';
            } else if (key == 'monitoring_channels' || key == 'validity_period_type') {
                formData[key] = 1;
            } else {
                formData[key] = [];
            }
        }
    }
    newDialog.visible = true;
};
const opeartRule = () => {};
//取消新建规则
const cancelnew = () => {
    newDialog.visible = false;
};
//确定新建规则/编辑规则
const submitnew = () => {
    formData.validity_period_start = time.value[0];
    formData.validity_period_end = time.value[1];
    formData.words_id_arr = formInline.tag_ids;
    formData.staff_id_arr = formInline.work_user_list;
    if (!formData.name) {
        ElMessage({ message: '规则名称不能为空！', type: 'warning' });
        return;
    }
    if (!formData.validity_period_type) {
        ElMessage({ message: '请选择有效期！', type: 'warning' });
        return;
    }
    if (!formData.monitoring_channels) {
        ElMessage({ message: '请选择监控渠道！', type: 'warning' });
        return;
    }
    if (formData.monitoring_object.length == 0) {
        ElMessage({ message: '请选择监控对象！', type: 'warning' });
        return;
    }
    if (formInline.work_user_list.length == 0) {
        ElMessage({ message: '请选择提醒设置！', type: 'warning' });
        return;
    }

    if (newDialog.title == '新建规则') {
        submitData();
    } else {
        editData();
    }
};
const newDialog = reactive({
    visible: false,
    title: '新建规则',
    width: '600px',
    cancel: cancelnew,
    submit: submitnew,
    cancelText: '取消',
    submitText: '确定'
});

const getDepart = (res: any) => {
    DepartRef.value.departVisble = false;
    creators.value = res;
    formInline.work_user_list = getSetionId('id', res);
};
//打开员工弹框
const opDepart = () => {
    if (formData.monitoring_channels == 1) {
        //私聊打开的是普通员工弹窗
        DepartRef.value.dataSourse = 0;
    } else {
        //群聊打开的是群主员工弹窗
        DepartRef.value.dataSourse = 1;
    }
    departTypeObj.itemData = {};
    DepartRef.value.appDialog.chooseArr = formInline.work_user_list;
    DepartRef.value.appDialog.isInit = true;
    DepartRef.value.appDialog.title = '选择员工';
    DepartRef.value.departVisble = true;
};
// 删除选中敏感词
const changeWord = (data: any) => {
    if (data.length > 0) {
        formInline.tag_ids = formInline.tag_ids.filter((item: any) => data.includes(item));
        tabsList.value = tabsList.value.filter((item: any) => data.includes(item.id));
    } else {
        formInline.tag_ids = [];
        tabsList.value = [];
    }
};
//删除员工
const changeDepart = (data: any) => {
    creators.value = creators.value.filter((item: any) => data.includes(item.id));
    formInline.work_user_list = formInline.work_user_lis.filter((item: any) => data.includes(item));
};

const openBatchLabel = () => {
    tagRef.value.openfirst();
    tagRef.value.chooseitem = tabsList.value;
    tagRef.value.chooseid = formInline.tag_ids;
    tagRef.value.appDialog.visible = true;
};
const gettag = (data: any) => {
    const delids = getSetionId('id', data.delData);
    const id = data.paramlist.allids.filter(val => {
        return !formInline.tag_ids.includes(val);
    });
    const item = data.paramlist.allitems.filter(val => {
        return !formInline.tag_ids.includes(val.id);
    });
    // 添加新选择的监控敏感词
    tabsList.value = tabsList.value.concat(item);
    tabsList.value = tabsList.value.filter(item => !delids.includes(item.id));
    // 过滤取消选中的监控敏感词
    formInline.tag_ids = formInline.tag_ids.concat(id);
    formInline.tag_ids = formInline.tag_ids.filter(item => !delids.includes(item));
};
//创建规则
const submitData = () => {
    creatRule(formData).then((res: any) => {
        ElMessage({ message: '创建规则成功', type: 'success' });
        newDialog.visible = false;
        // initpage()
        tableRef.value?.clearSelection();
        tableRef.value.reload();
    });
};
// 编辑规则
const editData = () => {
    const param = {
        ...formData,
        rule_id: rowData.id
    };
    editRule(param).then((res: any) => {
        ElMessage({ message: '编辑规则成功', type: 'success' });
        newDialog.visible = false;
        DepartRef.value.selectedMember = creators.value;
        // initpage()
        tableRef.value?.clearSelection();
        tableRef.value.reload();
    });
};

// 表格的自适应高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
onMounted(() => {
    reSize(getTableH);
    getTableH();
});
</script>
<style lang="scss" scoped>
.monitoringrules_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.search {
    background-color: #f9f9f9;
    padding: 16px 16px 0;
    display: flex;
    justify-content: space-between;
}

.table-top {
    display: flex;
    justify-content: flex-end;
    margin: 10px 0 15px;
}

.content {
    min-height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 14px;

    :deep(.el-form-item) {
        margin-bottom: 0;
    }

    .form-item {
        margin-bottom: 16px;
    }

    .form-option-item {
        margin-bottom: 8px;
    }

    .form-check-item {
        margin-bottom: 24px;

        .el-checkbox-group,
        .el-checkbox {
            height: auto;
            line-height: normal;
        }

        .el-checkbox-group {
            margin-top: -2px;
        }

        .el-checkbox {
            margin-top: 16px;
        }
    }

    :deep(.el-input__inner) {
        height: auto !important;
    }
}
</style>
